/**
 * Copyright 2023-2023 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "framework/model/unified_model/unified_model.h"
#include "framework/infra/log/log.h"
#include "infra/base/assertion.h"
#include "base/error_types.h"

namespace hiai {
FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY UnifiedModel::UnifiedModel(
    const uint8_t* modelData, size_t modelSize, bool isPassedFromHidl)
{
    modelData_ = modelData;
    modelSize_ = modelSize;
    if (Init(isPassedFromHidl) == hiai::SUCCESS) {
        isValid_ = true;
    }
}

// Models of Type IR_API_GRAPH_MODEL don't have ModelFileHeader
hiai::Status UnifiedModel::InitModelHeader()
{
    if (modelSize_ < sizeof(ModelFileHeader)) {
        FMK_LOGW("size of buffer < size of modelheader");
        modelHeader_ = Maybe<ModelFileHeader>(NULL_MAYBE);
        return hiai::SUCCESS;
    }

    ModelFileHeader modelHeader = *reinterpret_cast<const ModelFileHeader*>(modelData_);
    if (modelHeader.magic != MODEL_FILE_MAGIC_NUM) {
        modelHeader_ = Maybe<ModelFileHeader>(NULL_MAYBE);
        FMK_LOGW("cannot get modelheader magic");
        return hiai::SUCCESS;
    }

    HIAI_EXPECT_TRUE(sizeof(ModelFileHeader) + modelHeader.length == modelSize_);

    modelHeader_ = Maybe<ModelFileHeader>(modelHeader);
    return hiai::SUCCESS;
}

FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Maybe<ModelPartition> UnifiedModel::GetModelPartition(
    ModelPartitionType type, int8_t index) const
{
    return modelPartitions_.GetPartition(type, index);
}

FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY size_t UnifiedModel::GetModelPartitionsSize() const
{
    return modelPartitions_.GetPartitionsSize();
}

// for Load
hiai::Status UnifiedModel::Init(bool isPassedFromHidl)
{
    HIAI_EXPECT_TRUE(modelData_ != nullptr && modelSize_ > 0);
#ifdef PLATFORM_FPGA
    const int MODEL_SIZE_LIMIT = 209715200; // 200M: 209715200 = 200 * 1024 * 1024
    if (modelSize_ > MODEL_SIZE_LIMIT) {
        FMK_LOGE("Load model size:%zu is big for FPGA platform", modelSize_);
        return hiai::FAILURE;
    }
#endif
    HIAI_EXPECT_EXEC(InitModelHeader());
    if (modelHeader_.Exist()) {
        const uint8_t* partitionsData = modelData_ + sizeof(ModelFileHeader);
        size_t partitionsSize = modelSize_ - sizeof(ModelFileHeader);
        HIAI_EXPECT_EXEC(modelPartitions_.Init(partitionsData, partitionsSize, isPassedFromHidl));
    }
    return hiai::SUCCESS;
}
}